package com.geek.design_model.singleton;

import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CyclicBarrier;

/**
 * 双重检查的单例模式
 * @Author Hydra
 * @Date 2022/6/25 10:18
 */
@Slf4j
public class DoubleCheckSingleton {

    private  static DoubleCheckSingleton instance;
    public static DoubleCheckSingleton getInstance() {
        if(instance == null){
            synchronized (DoubleCheckSingleton.class){
                if(instance == null){
                    log.info("初始化对象");
                    instance = new DoubleCheckSingleton();
                }
            }
        }
        return instance;
    }
    private DoubleCheckSingleton(){}

    String test(){
        return "test";
    }

    static int THREAD_COUNT = 10;
    static CyclicBarrier cyclicBarrier = new CyclicBarrier(THREAD_COUNT);
    static class InstanceThread extends Thread{
        @SneakyThrows
        @Override
        public void run() {
            cyclicBarrier.await();
            DoubleCheckSingleton instance = DoubleCheckSingleton.getInstance();
            if(instance == null){
                log.info("--------------------");
            }
            log.info(instance.test());
        }
    }

    public static void main(String[] args) throws Exception {
        for (int i = 0; i < THREAD_COUNT; i++) {
            InstanceThread thread = new InstanceThread();
            thread.start();
        }
    }

}
